package cn.iocoder.yudao.module.promotion.controller.app.points;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.product.api.sku.ProductSkuApi;
import cn.iocoder.yudao.module.product.api.spu.ProductSpuApi;
import cn.iocoder.yudao.module.product.api.spu.dto.ProductSpuPageReqVO;
import cn.iocoder.yudao.module.product.api.spu.dto.ProductSpuRespDTO;
import cn.iocoder.yudao.module.promotion.controller.admin.points.pointsproduct.PointsProductPageReqVO;
import cn.iocoder.yudao.module.promotion.controller.admin.points.vo.pointsactivity.PointsActivityPageReqVO;
import cn.iocoder.yudao.module.promotion.controller.admin.points.vo.pointsactivity.PointsActivityRespVO;
import cn.iocoder.yudao.module.promotion.controller.admin.seckill.vo.activity.SeckillActivityPageReqVO;
import cn.iocoder.yudao.module.promotion.convert.points.PointsActivityConvert;
import cn.iocoder.yudao.module.promotion.dal.dataobject.points.PointsActivityDO;
import cn.iocoder.yudao.module.promotion.dal.dataobject.points.PointsProductDO;
import cn.iocoder.yudao.module.promotion.dal.dataobject.seckill.SeckillActivityDO;
import cn.iocoder.yudao.module.promotion.dal.dataobject.seckill.SeckillProductDO;
import cn.iocoder.yudao.module.promotion.service.points.PointsActivityService;
import cn.iocoder.yudao.module.promotion.service.points.PointsProductService;
import cn.iocoder.yudao.module.promotion.service.seckill.SeckillActivityService;
import cn.iocoder.yudao.module.system.api.dict.DictDataApi;
import cn.iocoder.yudao.module.system.api.dict.dto.DictDataRespDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;

@Tag(name = "管理后台 - 积分活动")
@RestController
@RequestMapping("/promotion/points-activity")
@Validated
public class AppPointsActivityController {

    @Resource
    private PointsActivityService pointsActivityService;

    @Resource
    private PointsProductService pointsProductService;

    @Resource
    private ProductSkuApi productSkuApi;

    @Resource
    private ProductSpuApi productSpuApi;

    @Resource
    private DictDataApi dictDataApi;

    @Resource
    private SeckillActivityService seckillActivityService;

    @GetMapping("/page")
    @Operation(summary = "获得积分活动分页")
    public CommonResult<List<PointsActivityRespVO>> getPointActivityPage(PointsActivityPageReqVO pageVO) {
        List<String> names = Arrays.asList(pageVO.getNames().split(","));
        pageVO.setNameList(names);
        List<PointsActivityDO> pageResult = pointsActivityService.pointsList(pageVO);
        if (CollUtil.isEmpty(pageResult)) {
            return success(Collections.emptyList());
        }
        List<PointsActivityRespVO> result = PointsActivityConvert.INSTANCE.convertList(pageResult);
        // 拼接返回
        for (PointsActivityRespVO pointsActivityRespVO : result) {
            PointsProductPageReqVO pointsProductPageReqVO = new PointsProductPageReqVO();
            pointsProductPageReqVO.setActivityId(pointsActivityRespVO.getId());
            pointsProductPageReqVO.setPageNo(pageVO.getPageNo());
            pointsProductPageReqVO.setPageSize(3);
            PageResult<PointsProductDO> productsList = pointsProductService.getPointsProductPage(pointsProductPageReqVO);
            List<Long> spuIds = convertList(productsList.getList(), PointsProductDO::getSpuId);
            List<ProductSpuRespDTO> spuList = productSpuApi.validateSpuList(spuIds);
            List<DictDataRespDTO> dictData = dictDataApi.getDictDataList("product_label");
            for (ProductSpuRespDTO pageReqVO : spuList) {
                Set<String> targetNumbers = Arrays.stream(pageReqVO.getProductLabel().replaceAll("[\\[\\]\\s]", "").split(","))
                        .collect(Collectors.toSet());
                List<DictDataRespDTO> filteredList = dictData.stream()
                        .filter(dto -> targetNumbers.stream().anyMatch(num -> dto.getValue().equals(num)))
                        .collect(Collectors.toList());
                String productLabel = filteredList.stream()
                        .map(DictDataRespDTO::getLabel) // 提取 value 字段
                        .collect(Collectors.joining(",")); // 用逗号连接
                pageReqVO.setProductLabel(productLabel);
            }
            pointsActivityRespVO.setProductSpuDOList(spuList);
        }
        return success(result);
    }

    @GetMapping("/spuPage")
    @Operation(summary = "获得积分活动分页")
    public CommonResult<PageResult<ProductSpuPageReqVO>> spuPage(PointsActivityPageReqVO pageVO) {
        // 拼接返回
        try{
            if(StringUtils.isNotBlank(pageVO.getName()) && pageVO.getName().equals("限时秒杀")){
                SeckillActivityPageReqVO sap = new SeckillActivityPageReqVO();
                sap.setName(pageVO.getName());
                List<SeckillActivityDO> pageResult = seckillActivityService.seckillList(sap);
                SeckillProductDO seckillProduct = new SeckillProductDO();
                seckillProduct.setActivityId(pageResult.get(0).getId());
                List<SeckillProductDO> seckillProductDOList = seckillActivityService.getSeckillProductList(seckillProduct);
                List<Long> spuIds = convertList(seckillProductDOList, SeckillProductDO::getSpuId);
                PageParam pageParam = new PageParam();
                pageParam.setPageNo(pageVO.getPageNo());
                pageParam.setPageSize(pageVO.getPageSize());
                PageResult<ProductSpuPageReqVO> spuList = productSpuApi.spuListForPoints(pageParam, spuIds);
                return success(spuList);
            }else{
                List<PointsActivityDO> pageResult = pointsActivityService.pointsList(pageVO);
                if (CollUtil.isEmpty(pageResult)) {
                    return success(PageResult.empty(null));
                }
                PointsProductPageReqVO pointsProductPageReqVO = new PointsProductPageReqVO();
                pointsProductPageReqVO.setActivityId(pageResult.get(0).getId());
                pointsProductPageReqVO.setPageNo(pageVO.getPageNo());
                pointsProductPageReqVO.setPageSize(pageVO.getPageSize());
                List<PointsProductDO> productsList = pointsProductService.getPointsProductList(pointsProductPageReqVO);
                List<Long> spuIds = convertList(productsList, PointsProductDO::getSpuId);
                PageParam pageParam = new PageParam();
                pageParam.setPageNo(pageVO.getPageNo());
                pageParam.setPageSize(pageVO.getPageSize());
                PageResult<ProductSpuPageReqVO> spuList;
                if(StringUtils.isNotBlank(pageVO.getName()) && pageVO.getName().equals("疯狂排行")){
                    spuList = productSpuApi.crazySpuListForPoints(pageParam, spuIds);
                }else{
                    spuList = productSpuApi.spuListForPoints(pageParam, spuIds);
                }
                if (CollUtil.isEmpty(spuList.getList())) {
                    return success(PageResult.empty(spuList.getTotal()));
                }
                List<DictDataRespDTO> dictData = dictDataApi.getDictDataList("product_label");
                for (ProductSpuPageReqVO pageReqVO : spuList.getList()) {
                    Set<String> targetNumbers = Arrays.stream(pageReqVO.getProductLabel().replaceAll("[\\[\\]\\s]", "").split(","))
                            .collect(Collectors.toSet());
                    List<DictDataRespDTO> filteredList = dictData.stream()
                            .filter(dto -> targetNumbers.stream().anyMatch(num -> dto.getValue().equals(num)))
                            .collect(Collectors.toList());
                    String productLabel = filteredList.stream()
                            .map(DictDataRespDTO::getLabel) // 提取 value 字段
                            .collect(Collectors.joining(",")); // 用逗号连接
                    pageReqVO.setProductLabel(productLabel);
                }
                return success(spuList);
            }
        }catch (Exception e){
            ErrorCode errorCode = new ErrorCode(500,e.getMessage());
            return error(errorCode);
        }
    }
}
